<script setup lang="ts">
/**
 * @name UserManagement
 * @description 用户管理
 */
import { Delete, Edit, Key } from '@element-plus/icons-vue'
import type {
  Action,
  FormInstance,
} from 'element-plus'
import {
  ElButton,
  ElSwitch,
} from 'element-plus'
import FormModal from './components/FormModal.vue'
import SearchForm from './components/SearchForm.vue'
import {
  defaultPagingParams,
  defaultUserForm,
  userFormRules,
} from './index'
import type {
  DepartmentalInfo,
  PartRequired,
  RoleInfo,
  TableColumn,
  UserInfo,
  UserQueryListParams,
  UserQueryListResult,
  UserSaveOrUpdateParams,
} from '@/types'
import { sysDepartmentalApi, sysUserApi } from '@/api'

// const { formTo, form, to, exclude } = useKeepPageStore();
// to('/home');
const { userInfo } = storeToRefs(useUserStore())
const { setUserInfo } = useUserStore()
const { $message, $confirm, $power } = useCurrentInstance()
const { withLoading, loading, spaceLoading }
  = useDefineLoading()
const [userList, setUserList] = useState<
  UserQueryListResult[]
>([])
const [userForm, setUserForm] = useState<
  Partial<UserSaveOrUpdateParams>
>({
  ...defaultUserForm,
})
const [isRoleDialog, setIsRoleDialog]
  = useState<boolean>(false)
const [isDepartmentDialog, setIsDepartmentDialog]
  = useState<boolean>(false)
const [total, setTotal] = useState<number>(0)
const [tableSelect, setTableSelect] = useState<
  UserQueryListResult[]
>([])
const [formModalTitle, setFormModalTitle]
  = useState<string>('')
const [departmentData, setDepartmentData] = useQuoteState<
  DepartmentalInfo[]
>([])
const [roleData, setRoleData] = useQuoteState<RoleInfo[]>(
  [],
)

const column: TableColumn<UserQueryListResult>[] = [
  { key: uuid(), type: 'selection', width: '55' },
  {
    key: uuid(),
    type: 'index',
    width: '80',
    label: '序号',
  },
  {
    key: uuid(),
    label: '用户名',
    prop: 'userName',
  },
  {
    key: uuid(),
    label: '登录账号',
    prop: 'loginName',
  },
  {
    key: uuid(),
    label: '角色',
    prop: 'roleName',
  },
  {
    key: uuid(),
    label: '部门',
    prop: 'departmentalName',
  },
  {
    key: uuid(),
    label: '所属企业',
    prop: 'tenantName',
  },
  {
    key: uuid(),
    label: '启用',
    render({ row }) {
      return h(ElSwitch, {
        modelValue: row?.enable,
        loading: loading.value,
        activeValue: 1,
        inactiveValue: 0,
        disabled: !$power('edit'),
        onChange: (val: string | number | boolean) =>
          handleStateChange(val, row.id),
      })

      // return (
      //   <ElSwitch
      //     modelValue={row?.enable}
      //     activeValue="1"
      //     inactiveValue="0"
      //     loading={loading.value}
      //     onChange={(val: string | number | boolean) =>
      //       handleStateChange(val, row.id)
      //     }
      //   />
      // );
    },
  },
  {
    key: uuid(),
    label: '邮箱',
    prop: 'email',
  },
  {
    key: uuid(),
    label: '电话',
    prop: 'phone',
  },
]

const pagingParams = ref<UserQueryListParams>({
  ...defaultPagingParams,
})
const formRef = ref<FormInstance>()
const departmentFormRef = ref<FormInstance>()
const modalRef = ref<InstanceType<typeof FormModal>>()
const currentShareDepartment = ref<number>(0)
const currentShareRole = ref<number>()

onMounted(async () => {
  getUserList()
  getDepartmentData()
  getRoleData()
})

async function getUserList() {
  const pagination = { ...toValue(pagingParams) }
  const { data } = await withLoading(sysUserApi.queryList)(
    pagination,
  )
  setUserList(data?.records ?? [])
  setTotal(data.total ?? 0)
}

/** 获取部门列表 */
async function getDepartmentData() {
  const { data: res }
    = await sysDepartmentalApi.queryTreeList()
  setDepartmentData(res)
}
async function getRoleData() {
  const { data: res } = await sysRoleApi.queryList({
    pageNumber: 1,
    pageSize: 999,
  })
  setRoleData(res?.records ?? [])
}
/** 删除数据 */
async function deleteData(id: number) {
  const res: Action = await $confirm(
    '该操作将永久删除该数据，确定删除？',
    '警告',
    {
      type: 'warning',
    },
  ).catch(e => e)

  if (res !== 'confirm')
    return
  const { message } = await sysUserApi.deleteUser(id)
  $message.success(message || '删除成功！')
  const o = [...userList.value]
  o.splice(id, 1)
  setUserList(o)
  getUserList()
}
async function saveOrUpdate(row: Partial<UserSaveOrUpdateParams>) {
  const params = toValue(row)
  removeUnnecessaryParams(params)

  const { message, code } = await sysUserApi.saveOrUpdate(
    params,
  )
  if (code !== 200)
    return
  $message.success(message ?? '操作成功')
  getUserList()
  modalRef.value?.close?.()
}
/** 显示编辑弹窗 */
async function showEditDialog(row: UserQueryListResult) {
  modalRef.value?.open()
  await nextTick()
  setFormModalTitle('编辑')
  setUserForm({ ...defaultUserForm, ...row })
}
/** 显示添加弹窗 */
async function showAddDialog() {
  modalRef.value?.open()
  await nextTick()
  setFormModalTitle('新增')
  setUserForm({
    ...defaultUserForm,
    id: undefined,
  })
}
async function showRoleDialog() {
  if (tableSelect.value.length === 0) {
    $message.warning('请先选中需要操作的数据！')
    return
  }
  formRef.value?.resetFields?.()
  await nextTick()
  setIsRoleDialog(true)
}
async function showDepartmentDialog() {
  if (tableSelect.value.length === 0) {
    $message.warning('请先选中需要操作的数据！')
    return
  }
  formRef.value?.resetFields?.()
  await nextTick()
  setIsDepartmentDialog(true)
}
async function shareRole() {
  const isValic = await formRef.value?.validate()
  if (!isValic || tableSelect.value.length === 0)
    return
  const n = tableSelect.value.map(item => ({
    userId: item.id as unknown as number,
    roleId: currentShareRole.value as number,
  }))
  const { code } = await sysRoleUserApi.batchUserId(n)
  if (code !== 200)
    return
  setIsRoleDialog(false)
  getUserList()
  $message.success('角色分配成功！')

  // ?修改本用户更新缓存信息
  const m = tableSelect.value.map(item => item.id)
  if (!m.includes(userInfo.value.id ?? 0))
    return
  setUserInfo({
    ...userInfo.value,
    roleId: currentShareRole.value as number,
  })
}
async function shareDepartment() {
  const isValic = await departmentFormRef.value?.validate()
  if (!isValic || tableSelect.value.length === 0)
    return
  const n = tableSelect.value.map<Partial<UserInfo>>(
    item => ({
      id: item.id,
      departmentalId: currentShareDepartment.value as number,
    }),
  )
  const { code } = await sysUserApi.batchUpdate(n)
  if (code !== 200)
    return
  setIsDepartmentDialog(false)
  getUserList()
  $message.success('部门分配成功！')
  // ?修改本用户更新缓存信息
  const m = tableSelect.value.map(item => item.id)
  if (!m.includes(userInfo.value.id ?? 0))
    return
  setUserInfo({
    ...userInfo.value,
    departmentalId: currentShareDepartment.value as number,
  })
}
async function handleStateChange(val: string | number | boolean, id: number) {
  const params: PartRequired<
    UserSaveOrUpdateParams,
    'id' | 'enable'
  > = {
    id,
    enable: val as UserSaveOrUpdateParams['enable'],
  }
  saveOrUpdate(params)
}
async function clickResetKey(row: UserQueryListResult) {
  const res: Action = await $confirm(
    h('div', [
      '确认要重置用户名为',
      h('strong', { style: 'margin: 0 5px' }, row.userName),
      '的密码吗？',
    ]),
    '操作提示',
    {
      type: 'warning',
    },
  ).catch(e => e)

  if (res !== 'confirm')
    return
  if (row.id) {
    const { code } = await sysUserApi.resetPassword(row.id)
    if (code === 200) {
      $message.success('重置密码成功，初始密码为123456')
    }
  }
}
</script>

<template>
  <div
    class="padding-sm flex-direction flex align-end container"
  >
    <view-table
      :columns="column"
      :loading="loading"
      :data="userList"
      :operate-width="200"
      :show-download="false"
      @selection-change="setTableSelect"
    >
      <template #actions>
        <!-- <div class="text-red">
          {{ loading }}{{ spaceLoading }}
        </div> -->
        <SearchForm
          v-model="pagingParams"
          @plus="showAddDialog"
          @reset="getUserList"
          @search="getUserList"
          @assign-department="showDepartmentDialog"
          @assign-role="showRoleDialog"
        />
      </template>
      <template #operate="{ row }">
        <TdButton
          title="重置密码"
          :icon="Key"
          type="warning"
          :disabled="!$power('edit')"
          @click="clickResetKey(row)"
        />
        <ElDivider direction="vertical" />
        <TdButton
          title="编辑"
          :icon="Edit"
          type="primary"
          @click="showEditDialog(row)"
        />
        <el-divider direction="vertical" />
        <TdButton
          title="删除"
          :icon="Delete"
          type="danger"
          @click="deleteData(row.id)"
        />
      </template>
    </view-table>
    <!-- 分页 -->
    <ListsPagination
      v-model:page-num="pagingParams.pageNumber"
      v-model:page-size="pagingParams.pageSize"
      :total="total"
      @current-change="getUserList"
      @size-change="getUserList"
    />
    <!-- 分配部门 -->
    <el-dialog
      v-model="isDepartmentDialog"
      width="600"
      title="分配部门"
      append-to-body
    >
      <el-form
        ref="departmentFormRef"
        :model="{ currentShareDepartment }"
        :rules="userFormRules"
        label-width="100px"
        label-position="right"
        class=""
      >
        <el-form-item
          prop="currentShareDepartment"
          label="分配部门"
        >
          <el-cascader
            v-model="currentShareDepartment"
            placeholder="请选择部门"
            :options="departmentData"
            :props="{
              label: 'departName',
              emitPath: false,
              checkStrictly: true,
              value: 'id',
            }"
            filterable
            class="width-fill"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <ElButton @click="setIsDepartmentDialog(false)">
          取 消
        </ElButton>
        <ElButton type="primary" @click="shareDepartment">
          确 定
        </ElButton>
      </template>
    </el-dialog>
    <!-- 分配角色 -->
    <el-dialog
      v-model="isRoleDialog"
      width="600"
      title="分配角色"
      append-to-body
    >
      <el-form
        ref="formRef"
        :model="{ currentShareRole }"
        :rules="userFormRules"
        label-width="100px"
        label-position="right"
        class="width-fill"
      >
        <el-form-item
          prop="currentShareRole"
          label="分配角色"
          class="width-fill flex"
        >
          <el-select
            v-model="currentShareRole"
            class="width-fill"
            placeholder="请选择角色" filterable clearable
          >
            <el-option
              v-for="item in roleData"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <ElButton @click="setIsRoleDialog(false)">
          取 消
        </ElButton>
        <ElButton type="primary" @click="shareRole">
          确 定
        </ElButton>
      </template>
    </el-dialog>
    <FormModal
      ref="modalRef"
      v-model:data="userForm"
      :title="formModalTitle"
      @save-success="saveOrUpdate(userForm)"
    />
  </div>
</template>
